<template>
  <div class="algorithm-detail">
    <!-- 加载状态 -->
    <div v-if="algorithmsStore.isLoading" class="loading-state">
      <n-spin size="large" />
    </div>
    
    <!-- 题目不存在 -->
    <div v-else-if="!currentAlgorithm" class="error-state">
      <n-result status="404" title="题目不存在" description="请检查题目ID是否正确">
        <template #footer>
          <n-button @click="$router.push('/algorithms')">
            返回题库
          </n-button>
        </template>
      </n-result>
    </div>
    
    <!-- 题目详情 -->
    <div v-else class="detail-content">
      <!-- 头部导航 -->
      <div class="detail-header">
        <div class="header-left">
          <n-button 
            quaternary 
            @click="$router.back()"
          >
            <template #icon>
              <n-icon><ArrowLeft /></n-icon>
            </template>
            返回
          </n-button>
          
          <div class="title-section">
            <h1 class="algorithm-title">{{ currentAlgorithm.title }}</h1>
            <div class="algorithm-meta">
              <n-tag 
                :type="getDifficultyType(currentAlgorithm.difficulty)"
                size="small"
              >
                {{ getDifficultyText(currentAlgorithm.difficulty) }}
              </n-tag>
              <span class="meta-item">
                <n-icon size="14"><Clock /></n-icon>
                {{ formatDate(currentAlgorithm.createdAt, 'YYYY-MM-DD HH:mm') }}
              </span>
            </div>
          </div>
        </div>
        
        <div class="header-right">
          <n-button-group>
            <n-button 
              @click="showEditModal = true"
            >
              <template #icon>
                <n-icon><Edit /></n-icon>
              </template>
              编辑
            </n-button>
            
            <n-button 
              type="error"
              @click="handleDelete"
            >
              <template #icon>
                <n-icon><Trash /></n-icon>
              </template>
              删除
            </n-button>
          </n-button-group>
        </div>
      </div>
      
      <!-- 主要内容区域 -->
      <div class="detail-main">
        <!-- 左侧：题目描述 -->
        <div class="problem-section">
          <n-card title="题目描述" class="problem-card">
            <div class="problem-content">
              <div class="problem-description">
                {{ currentAlgorithm.description }}
              </div>
              
              <!-- 如果有图片，显示图片 -->
              <div v-if="currentAlgorithm.imageUrl" class="problem-image">
                <n-image
                  :src="currentAlgorithm.imageUrl"
                  :alt="currentAlgorithm.title"
                  object-fit="contain"
                  preview-disabled
                />
              </div>
            </div>
          </n-card>
          
          <!-- 解题思路（如果有的话） -->
          <n-card v-if="currentSolution?.notes" title="解题思路" class="notes-card">
            <div class="notes-content">
              {{ currentSolution.notes }}
            </div>
          </n-card>
        </div>
        
        <!-- 右侧：代码编辑器 -->
        <div class="editor-section">
          <n-card class="editor-card">
            <template #header>
              <div class="editor-header">
                <span>代码编辑器</span>
                <div class="editor-actions">
                  <n-select
                    v-model:value="selectedLanguage"
                    :options="languageOptions"
                    style="width: 120px; margin-right: 12px"
                    size="small"
                  />
                  
                  <n-button-group size="small">
                    <n-button 
                      :loading="isSaving"
                      type="primary"
                      @click="handleSaveCode"
                    >
                      <template #icon>
                        <n-icon><DeviceFloppy /></n-icon>
                      </template>
                      保存
                    </n-button>
                    
                    <n-button 
                      @click="handleFormatCode"
                    >
                      <template #icon>
                        <n-icon><Code /></n-icon>
                      </template>
                      格式化
                    </n-button>
                    
                    <n-button 
                      @click="handleResetCode"
                    >
                      <template #icon>
                        <n-icon><Refresh /></n-icon>
                      </template>
                      重置
                    </n-button>
                  </n-button-group>
                </div>
              </div>
            </template>
            
            <div class="editor-container">
              <MonacoEditor
                v-model="codeContent"
                :language="selectedLanguage"
                :height="editorHeight"
                :options="editorOptions"
                @change="handleCodeChange"
              />
            </div>
            
            <!-- 编辑器状态栏 -->
            <div class="editor-status">
              <div class="status-left">
                <span class="status-item">
                  行数: {{ codeStats.lines }}
                </span>
                <span class="status-item">
                  字符: {{ codeStats.characters }}
                </span>
                <span v-if="lastSavedTime" class="status-item">
                  最后保存: {{ formatRelativeTime(lastSavedTime) }}
                </span>
              </div>
              
              <div class="status-right">
                <span 
                  class="save-status"
                  :class="{ 
                    saved: !hasUnsavedChanges,
                    unsaved: hasUnsavedChanges 
                  }"
                >
                  {{ hasUnsavedChanges ? '未保存' : '已保存' }}
                </span>
              </div>
            </div>
          </n-card>
        </div>
      </div>
    </div>
    
    <!-- 编辑题目模态框 -->
    <n-modal 
      v-model:show="showEditModal" 
      preset="card" 
      title="编辑题目" 
      style="width: 600px"
    >
      <n-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-placement="top"
      >
        <n-form-item path="title" label="题目标题">
          <n-input 
            v-model:value="editForm.title" 
            placeholder="请输入题目标题"
          />
        </n-form-item>
        
        <n-form-item path="difficulty" label="难度">
          <n-select
            v-model:value="editForm.difficulty"
            placeholder="选择难度"
            :options="difficultyOptions"
          />
        </n-form-item>
        
        <n-form-item path="description" label="题目描述">
          <n-input 
            v-model:value="editForm.description" 
            type="textarea" 
            placeholder="请输入题目描述"
            :rows="6"
          />
        </n-form-item>
      </n-form>
      
      <template #footer>
        <div class="modal-footer">
          <n-button @click="showEditModal = false">取消</n-button>
          <n-button 
            type="primary" 
            :loading="algorithmsStore.isLoading"
            @click="handleUpdateAlgorithm"
          >
            保存
          </n-button>
        </div>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  NButton,
  NButtonGroup,
  NIcon,
  NTag,
  NCard,
  NImage,
  NSelect,
  NSpin,
  NResult,
  NModal,
  NForm,
  NFormItem,
  NInput,
  useMessage,
  useDialog,
  type FormInst,
  type FormRules
} from 'naive-ui'
import {
  ArrowLeft,
  Clock,
  Edit,
  Trash,
  DeviceFloppy,
  Code,
  Refresh
} from '@vicons/tabler'
import MonacoEditor from '@/components/common/MonacoEditor.vue'
import { useAlgorithmsStore } from '@/stores/algorithms'
import { useCalendarStore } from '@/stores/calendar'
import { 
  formatDate, 
  formatRelativeTime, 
  getDifficultyText 
} from '@/utils'
import type { UpdateAlgorithmRequest } from '@/types/algorithm'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const algorithmsStore = useAlgorithmsStore()
const calendarStore = useCalendarStore()

// 表单引用
const editFormRef = ref<FormInst | null>(null)

// 算法题目ID
const algorithmId = computed(() => parseInt(route.params.id as string))

// 当前算法题目
const currentAlgorithm = computed(() => 
  algorithmsStore.problems.find((a: any) => a.id === algorithmId.value)
)

// 当前解决方案
const currentSolution = computed(() => 
  algorithmsStore.currentSolution
)

// 编辑器相关状态
const selectedLanguage = ref('javascript')
const codeContent = ref('')
const editorHeight = ref('500px')
const isSaving = ref(false)
const hasUnsavedChanges = ref(false)
const lastSavedTime = ref<string | null>(null)

// 模态框状态
const showEditModal = ref(false)

// 编辑表单
const editForm = ref<{
  title: string
  difficulty: string
  description: string
}>({
  title: '',
  difficulty: '',
  description: ''
})

// 语言选项
const languageOptions = [
  { label: 'JavaScript', value: 'javascript' },
  { label: 'TypeScript', value: 'typescript' },
  { label: 'Python', value: 'python' },
  { label: 'Java', value: 'java' },
  { label: 'C++', value: 'cpp' },
  { label: 'C', value: 'c' },
  { label: 'Go', value: 'go' },
  { label: 'Rust', value: 'rust' }
]

// 难度选项
const difficultyOptions = [
  { label: '简单', value: 'easy' },
  { label: '中等', value: 'medium' },
  { label: '困难', value: 'hard' }
]

// 编辑器选项
const editorOptions = {
  minimap: { enabled: false },
  fontSize: 14,
  lineNumbers: 'on' as const,
  roundedSelection: false,
  scrollBeyondLastLine: false,
  automaticLayout: true,
  tabSize: 2,
  wordWrap: 'on' as const
}

// 表单验证规则
const editRules: FormRules = {
  title: [
    {
      required: true,
      message: '请输入题目标题',
      trigger: ['input', 'blur']
    }
  ],
  difficulty: [
    {
      required: true,
      message: '请选择难度',
      trigger: ['change', 'blur']
    }
  ],
  description: [
    {
      required: true,
      message: '请输入题目描述',
      trigger: ['input', 'blur']
    }
  ]
}

// 计算属性
const codeStats = computed(() => {
  const lines = codeContent.value.split('\n').length
  const characters = codeContent.value.length
  return { lines, characters }
})

// 获取难度类型
const getDifficultyType = (difficulty: string): 'default' | 'success' | 'warning' | 'error' | 'primary' | 'info' => {
  const types: Record<string, 'default' | 'success' | 'warning' | 'error' | 'primary' | 'info'> = {
    easy: 'success',
    medium: 'warning',
    hard: 'error'
  }
  return types[difficulty] || 'default'
}

// 处理代码变化
const handleCodeChange = () => {
  hasUnsavedChanges.value = true
}

// 保存代码
const handleSaveCode = async () => {
  if (!currentAlgorithm.value) return
  
  isSaving.value = true
  
  try {
    await algorithmsStore.saveSolution(currentAlgorithm.value.id, codeContent.value)
    
    hasUnsavedChanges.value = false
    lastSavedTime.value = new Date().toISOString()
    message.success('代码保存成功')
    
    // 记录活动
    await calendarStore.recordActivity({ date: new Date().toISOString().split('T')[0], count: 1 })
  } catch (error) {
    message.error('保存代码失败')
  } finally {
    isSaving.value = false
  }
}

// 格式化代码
const handleFormatCode = () => {
  // Monaco编辑器会自动格式化
  message.info('代码已格式化')
}

// 重置代码
const handleResetCode = () => {
  dialog.warning({
    title: '确认重置',
    content: '确定要重置代码吗？未保存的更改将丢失。',
    positiveText: '重置',
    negativeText: '取消',
    onPositiveClick: () => {
      codeContent.value = getDefaultCode(selectedLanguage.value)
      hasUnsavedChanges.value = true
      message.success('代码已重置')
    }
  })
}

// 获取默认代码模板
const getDefaultCode = (language: string): string => {
  const templates: Record<string, string> = {
    javascript: `// JavaScript 解决方案
function solution() {
    // 在这里编写你的代码
    
}`,
    typescript: `// TypeScript 解决方案
function solution(): any {
    // 在这里编写你的代码
    
}`,
    python: `# Python 解决方案
def solution():
    # 在这里编写你的代码
    pass`,
    java: `// Java 解决方案
public class Solution {
    public void solution() {
        // 在这里编写你的代码
        
    }
}`,
    cpp: `// C++ 解决方案
#include <iostream>
using namespace std;

void solution() {
    // 在这里编写你的代码
    
}`,
    c: `// C 解决方案
#include <stdio.h>

void solution() {
    // 在这里编写你的代码
    
}`,
    go: `// Go 解决方案
package main

import "fmt"

func solution() {
    // 在这里编写你的代码
    
}`,
    rust: `// Rust 解决方案
fn solution() {
    // 在这里编写你的代码
    
}`
  }
  
  return templates[language] || '// 开始编写你的代码\n'
}

// 编辑题目
const handleUpdateAlgorithm = async () => {
  if (!editFormRef.value || !currentAlgorithm.value) return
  
  try {
    await editFormRef.value.validate()
    
    const updateData: UpdateAlgorithmRequest = {
      title: editForm.value.title,
      difficulty: editForm.value.difficulty as 'easy' | 'medium' | 'hard',
      description: editForm.value.description
    }
    
    await algorithmsStore.updateProblem(currentAlgorithm.value.id, updateData)
    
    showEditModal.value = false
    message.success('题目更新成功')
  } catch (error) {
    console.error('Update algorithm failed:', error)
  }
}

// 删除题目
const handleDelete = () => {
  if (!currentAlgorithm.value) return
  
  dialog.warning({
    title: '确认删除',
    content: `确定要删除题目「${currentAlgorithm.value.title}」吗？此操作不可恢复。`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await algorithmsStore.deleteProblem(currentAlgorithm.value!.id)
        message.success('题目删除成功')
        router.push('/algorithms')
      } catch (error) {
        message.error('删除题目失败')
      }
    }
  })
}

// 自动保存
let autoSaveTimer: number | null = null

const startAutoSave = () => {
  if (autoSaveTimer) {
    clearInterval(autoSaveTimer)
  }
  
  autoSaveTimer = setInterval(() => {
    if (hasUnsavedChanges.value && codeContent.value.trim()) {
      handleSaveCode()
    }
  }, 30000) // 30秒自动保存
}

const stopAutoSave = () => {
  if (autoSaveTimer) {
    clearInterval(autoSaveTimer)
    autoSaveTimer = null
  }
}

// 监听语言变化
watch(selectedLanguage, (newLanguage) => {
  if (!codeContent.value.trim() || codeContent.value === getDefaultCode(selectedLanguage.value)) {
    codeContent.value = getDefaultCode(newLanguage)
  }
})

// 监听算法题目变化
watch(currentAlgorithm, (algorithm) => {
  if (algorithm) {
    editForm.value = {
      title: algorithm.title,
      difficulty: algorithm.difficulty,
      description: algorithm.description
    }
  }
}, { immediate: true })

// 监听解决方案变化
watch(currentSolution, (solution) => {
  if (solution) {
    codeContent.value = solution.code || getDefaultCode(selectedLanguage.value)
    selectedLanguage.value = solution.language || 'javascript'
    hasUnsavedChanges.value = false
    lastSavedTime.value = solution.savedAt.toISOString()
  } else {
    codeContent.value = getDefaultCode(selectedLanguage.value)
    hasUnsavedChanges.value = false
    lastSavedTime.value = null
  }
}, { immediate: true })

// 初始化数据
const initData = async () => {
  try {
    // 获取算法题目详情
    await algorithmsStore.fetchProblem(algorithmId.value)
    
    // 获取代码解决方案
    // await algorithmsStore.fetchCode(algorithmId.value)
  } catch (error) {
    console.error('Failed to load algorithm detail:', error)
  }
}

// 页面离开前提醒保存
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
  if (hasUnsavedChanges.value) {
    event.preventDefault()
    event.returnValue = ''
  }
}

// 组件挂载和卸载
onMounted(() => {
  initData()
  startAutoSave()
  window.addEventListener('beforeunload', handleBeforeUnload)
  
  // 调整编辑器高度
  nextTick(() => {
    const updateEditorHeight = () => {
      const windowHeight = window.innerHeight
      const headerHeight = 120
      const footerHeight = 60
      const padding = 100
      editorHeight.value = `${windowHeight - headerHeight - footerHeight - padding}px`
    }
    
    updateEditorHeight()
    window.addEventListener('resize', updateEditorHeight)
  })
})

onUnmounted(() => {
  stopAutoSave()
  window.removeEventListener('beforeunload', handleBeforeUnload)
})
</script>

<style scoped>
.algorithm-detail {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.loading-state,
.error-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.header-left {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.title-section {
  flex: 1;
}

.algorithm-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.algorithm-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #6b7280;
}

.detail-main {
  display: grid;
  grid-template-columns: 400px 1fr;
  gap: 24px;
  height: calc(100vh - 200px);
}

.problem-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
}

.problem-card,
.notes-card {
  border-radius: 12px;
}

.problem-content {
  line-height: 1.6;
}

.problem-description {
  color: #374151;
  white-space: pre-wrap;
  margin-bottom: 16px;
}

.problem-image {
  text-align: center;
}

.notes-content {
  color: #374151;
  line-height: 1.6;
  white-space: pre-wrap;
}

.editor-section {
  display: flex;
  flex-direction: column;
}

.editor-card {
  border-radius: 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.editor-actions {
  display: flex;
  align-items: center;
}

.editor-container {
  flex: 1;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
}

.editor-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f9fafb;
  border-top: 1px solid #e5e7eb;
  font-size: 12px;
  color: #6b7280;
}

.status-left {
  display: flex;
  gap: 16px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.save-status {
  font-weight: 500;
}

.save-status.saved {
  color: #059669;
}

.save-status.unsaved {
  color: #dc2626;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .detail-main {
    grid-template-columns: 1fr;
    height: auto;
  }
  
  .problem-section {
    order: 2;
    max-height: none;
    overflow-y: visible;
  }
  
  .editor-section {
    order: 1;
  }
}

@media (max-width: 768px) {
  .algorithm-detail {
    padding: 16px;
  }
  
  .detail-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-left {
    flex-direction: column;
    gap: 12px;
  }
  
  .algorithm-title {
    font-size: 20px;
  }
  
  .editor-actions {
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }
  
  .editor-actions > * {
    width: 100%;
  }
}
</style>